#include "MainWindow.h"
#include "ui_MainWindow.h"
#include <QtSql>

#include <QCheckBox>
#include <QAction>
#include <QFileDialog>
#include <QLabel>
#include <QDebug>

#include "OpenFile.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    m_db = QSqlDatabase::addDatabase("SQLITECIPHER");

    m_openFileUI = new OpenFile();

    createMenu();

    m_isAutoQuery = new QCheckBox("Auto Query");
    m_statusInfo = new QLabel();
    this->statusBar()->addWidget(m_isAutoQuery);
    this->statusBar()->addWidget(m_statusInfo);

    connect(m_openFileUI,&OpenFile::openDBFile,this,&MainWindow::onOpenDB);
    connect(ui->tables,&QListWidget::clicked,this,&MainWindow::onClickTables);
    connect(ui->queryBtn,&QPushButton::clicked,this,&MainWindow::onQuery);
    connect(ui->execBtn,&QPushButton::clicked,this,&MainWindow::onExec);
    connect(ui->clearBtn,&QPushButton::clicked,this,&MainWindow::onClearContent);
    connect(ui->records,&QTableWidget::cellChanged,this,&MainWindow::onRecordItemChanged);
    connect(ui->records,&QTableWidget::cellDoubleClicked,this,&MainWindow::onRecordClick);

    connect(ui->records->horizontalHeader(),&QHeaderView::sectionClicked,[this](int index){
        const QString colName = ui->records->horizontalHeaderItem(index)->text();
        static bool orderByFlag = false;
        QString sql;
        if (orderByFlag) {
            sql = QString("select * from %1 order by %2").arg(getCurrentTable()).arg(colName);
        } else {
            sql = QString("select * from %1 order by %2 DESC").arg(getCurrentTable()).arg(colName);
        }
        orderByFlag = !orderByFlag;
        innerRecordFullQuery(sql);
    });
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::createMenu()
{
    m_fileOpenAction = new QAction("Open");
    connect(m_fileOpenAction,&QAction::triggered,this,&MainWindow::onOpenFile);

    m_fileExitAction = new QAction("Close");
    connect(m_fileExitAction,&QAction::triggered,this,&MainWindow::onExit);


    QMenu *fileMenu = menuBar()->addMenu("File");
    fileMenu->addAction(m_fileOpenAction);
    fileMenu->addAction(m_fileExitAction);
}

void MainWindow::onOpenFile()
{
    m_openFileUI->show();
}

void MainWindow::onExit()
{

}

void MainWindow::onClickTables(const QModelIndex &index)
{
    if (!m_db.isOpen()) {
        qDebug() << "error";
        return;
    }

    QSqlRecord record = m_db.record(ui->tables->item(index.row())->text());

    QStringList headers;
    for (int i = 0; i < record.count(); ++i) {
        headers += record.fieldName(i);
    }

    ui->records->clearContents();
    ui->records->setRowCount(0);

    ui->records->setColumnCount(record.count());
    ui->records->setHorizontalHeaderLabels(headers);

    if (m_isAutoQuery->isChecked())
        onQuery();
}

void MainWindow::onQuery()
{
    QString sqlStr = QString("select * from %1").arg(getCurrentTable());

    innerRecordFullQuery(sqlStr);
}

void MainWindow::onExec()
{
    if (ui->tables->currentItem()->text().isEmpty())
        return;

    //TODO execute sql command
}

void MainWindow::onClearContent()
{
    ui->records->clearContents();
    ui->records->setRowCount(0);
}

void MainWindow::onRecordClick(int row,int column)
{
    qDebug() << row << column;
}

void MainWindow::onRecordItemChanged(int row,int column)
{
//    qDebug() << "changed";
    //TODO update change item
}

QString MainWindow::getCurrentTable() const
{
    const QString &table = ui->tables->currentItem()->text();

    if (table.isEmpty()) {
        qDebug() << "error" << table.isEmpty();
        return "";
    }
    return table;
}

void MainWindow::innerRecordFullQuery(const QString &sql)
{
    m_statusInfo->setText("query...");

    QSqlQuery query;
    query.prepare(sql);
    bool isQueryed = query.exec();

    ui->records->clearContents();
    ui->records->setRowCount(0);

    if (isQueryed) {
        auto colums = ui->records->columnCount();

        while(query.next()) {
            int row = ui->records->rowCount();
            ui->records->insertRow(row);
            for (int col = 0; col < colums; ++col) {
                ui->records->setItem(row,col,new QTableWidgetItem(query.value(col).toString()));
            }
        }
    }
    m_statusInfo->setText("query over!");
}

void MainWindow::onOpenDB(const QString &fileName,const QString &pass)
{
    qDebug() << fileName << pass;
    m_db.setDatabaseName(fileName);
    m_db.setPassword(pass);
    m_db.setConnectOptions("QSQLITE_USE_CIPHER=cipher; QSQLITE_ENABLE_REGEXP");
    if (!m_db.open()) {
        qDebug() << "Can not open connection: " << m_db.lastError().driverText();
    }

    QStringList tables = m_db.tables();
    ui->tables->addItems(tables);
}

